import { BaseService } from '../framework/base-service.js'
import path from 'path'
import _ from 'lodash'

export default class StaticService extends BaseService {
  static metadata = {
    name: 'static',
    dependencies: [],
    singleton: true
  }
  
  constructor() {
    super()
    this.mimeTypes = {
      '.html': 'text/html',
      '.js': 'application/javascript',
      '.css': 'text/css',
      '.json': 'application/json',
      '.png': 'image/png',
      '.jpg': 'image/jpeg',
      '.gif': 'image/gif',
      '.svg': 'image/svg+xml',
      '.ico': 'image/x-icon',
      '.woff': 'font/woff',
      '.woff2': 'font/woff2',
      '.ttf': 'font/ttf',
      '.eot': 'application/vnd.ms-fontobject'
    }
  }
  
  async onInit() {
    // 设置静态文件目录
    this.publicDir = path.join(process.cwd(), 'public')
    this.appsDir = path.join(process.cwd(), 'apps')
    this.packagesDir = path.join(process.cwd(), 'packages')
    
    this.logger.info('StaticService', '✅ Static service initialized')
    this.logger.info('StaticService', `Public dir: ${this.publicDir}`)
    this.logger.info('StaticService', `Apps dir: ${this.appsDir}`)
    this.logger.info('StaticService', `Packages dir: ${this.packagesDir}`)
  }
  
  registerRoutes(app) {
    // 首页重定向
    app.get('/', c => {
      c.redirect('/index.html')
      return c.text('')
    })
    
    // 静态文件服务
    app.get('/*', async c => {
      const urlPath = c.req.path
      
      // 安全检查：防止路径遍历
      if (urlPath.includes('..')) {
        return c.text('Forbidden', 403)
      }
      
      try {
        // 尝试不同的目录
        const file = await this.findFile(urlPath)
        
        if (file) {
          const ext = path.extname(urlPath).toLowerCase()
          const mimeType = this.mimeTypes[ext] || 'application/octet-stream'
          
          // 设置缓存头
          if (this.shouldCache(urlPath)) {
            c.header('Cache-Control', 'public, max-age=31536000')
          } else {
            c.header('Cache-Control', 'no-cache')
          }
          
          c.header('Content-Type', mimeType)
          return new Response(file)
        }
        
        // 未找到文件
        return this.handle404(c)
      } catch (err) {
        this.logger.error('StaticService', 'Error serving static file:', { 
          path: urlPath, 
          error: err.message 
        })
        return c.text('Internal Server Error', 500)
      }
    })
    
    return true
  }
  
  async findFile(urlPath) {
    // 移除开头的斜杠
    const cleanPath = urlPath.startsWith('/') ? urlPath.slice(1) : urlPath
    
    // 按优先级尝试不同的目录
    const searchPaths = this.getSearchPaths(cleanPath)
    
    for (const searchPath of searchPaths) {
      try {
        const file = Bun.file(searchPath)
        if (await file.exists()) {
          this.logger.debug('StaticService', `Serving file: ${searchPath}`)
          return file
        }
      } catch (err) {
        // 继续尝试下一个路径
        continue
      }
    }
    
    return null
  }
  
  getSearchPaths(urlPath) {
    const paths = []
    
    // 根据路径前缀决定搜索位置
    if (urlPath.startsWith('apps/')) {
      // 应用文件
      paths.push(path.join(process.cwd(), urlPath))
    } else if (urlPath.startsWith('packages/')) {
      // 包文件
      paths.push(path.join(process.cwd(), urlPath))
    } else if (urlPath.startsWith('_/')) {
      // 特殊路径（地图瓦片等）
      paths.push(path.join(this.publicDir, urlPath))
    } else {
      // 一般静态文件
      paths.push(path.join(this.publicDir, urlPath))
      
      // 如果是根路径文件，也尝试apps目录
      if (!urlPath.includes('/')) {
        paths.push(path.join(this.appsDir, urlPath))
      }
      
      // 默认文件
      if (!urlPath || urlPath === '' || urlPath.endsWith('/')) {
        paths.push(path.join(this.publicDir, 'index.html'))
        paths.push(path.join(this.appsDir, 'index.html'))
      }
    }
    
    return paths
  }
  
  shouldCache(urlPath) {
    // 这些文件类型应该被缓存
    const cacheableExtensions = [
      '.js', '.css', '.png', '.jpg', '.jpeg', '.gif', 
      '.svg', '.ico', '.woff', '.woff2', '.ttf', '.eot'
    ]
    
    // 这些路径应该被缓存
    const cacheablePaths = [
      '/packages/',
      '/imgs/',
      '/_/'
    ]
    
    const ext = path.extname(urlPath).toLowerCase()
    
    // 检查扩展名
    if (cacheableExtensions.includes(ext)) {
      // 但是如果文件名包含版本号或时间戳，则不缓存
      if (urlPath.includes('.min.') || urlPath.includes('.prod.')) {
        return true
      }
      
      // 检查路径
      return _(cacheablePaths).some(p => urlPath.startsWith(p))
    }
    
    return false
  }
  
  handle404(c) {
    // 如果是API请求，返回JSON
    if (c.req.path.startsWith('/api/')) {
      return c.json({ error: 'Not Found' }, 404)
    }
    
    // 否则返回HTML 404页面
    const html404 = `
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>404 - 页面未找到</title>
  <style>
    body {
      font-family: system-ui, -apple-system, sans-serif;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      margin: 0;
      background: #f5f5f5;
    }
    .container {
      text-align: center;
      padding: 2rem;
    }
    h1 {
      font-size: 6rem;
      margin: 0;
      color: #333;
    }
    p {
      font-size: 1.2rem;
      color: #666;
      margin: 1rem 0;
    }
    a {
      color: #007bff;
      text-decoration: none;
    }
    a:hover {
      text-decoration: underline;
    }
  </style>
</head>
<body>
  <div class="container">
    <h1>404</h1>
    <p>页面未找到</p>
    <p>请求的页面不存在或已被移动</p>
    <p><a href="/">返回首页</a></p>
  </div>
</body>
</html>`
    
    c.header('Content-Type', 'text/html; charset=utf-8')
    return c.html(html404, 404)
  }
}